package server;

import java.io.IOException;
import java.io.InputStream;

/**
 * 把请求信息封装为Request对象（根据InputSteam输入流封装）
 */
public class Request {

    private String method; // 请求方式，比如GET/POST
    private String url;  // 例如 /,/index.html

    private InputStream inputStream;  // 输入流，其他属性从输入流中解析出来


    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public Request() {
    }


    // 构造器，输入流传入
    public Request(InputStream inputStream) throws IOException {
        this.inputStream = inputStream;

        // 从输入流中获取请求信息，之所以要循环是由于io流的数据可能还没传过来
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }

        byte[] bytes = new byte[count];
        inputStream.read(bytes);

        String inputStr = new String(bytes);
        /**
         * GET / HTTP/1.1
         * Host: localhost:8080
         * Connection: keep-alive
         * Cache-Control: max-age=0
         * Upgrade-Insecure-Requests: 1
         * User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36
         * Sec-Fetch-Dest: document
         * Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,'*'/'*';
         *  q = 0.8, application / signed - exchange;
         *         v = b3;
         *         q = 0.9
         *                 * Sec - Fetch - Site:none
         *                 * Sec - Fetch - Mode:navigate
         *                 * Sec - Fetch - User: ?1
         *                 * Accept - Encoding:gzip, deflate, br
         *                 * Accept - Language:zh - CN, zh;
         *         q = 0.9
         *                 * Cookie:SSO_LANG_V2 = zh - CN
         */
        // 获取第一行请求头信息
        String firstLineStr = inputStr.split("\\n")[0];  // GET / HTTP/1.1

        String[] strings = firstLineStr.split(" ");

        this.method = strings[0];
        this.url = strings[1];

        System.out.println("=====>>method:" + method);
        System.out.println("=====>>url:" + url);


    }
}
